package com.biz.hunter.service.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.biz.hunter.cache.EhCacheElement;
import com.biz.hunter.cache.EhCacheFactory;
import com.biz.qq.wechat.api.AccessTokenAPI;
import com.biz.qq.wechat.api.JSTicketAPI;
import com.biz.qq.wechat.entity.AccessToken;
import com.biz.qq.wechat.entity.JSTicket;
import com.biz.system.config.WebchatServiceConstant;

@Service
public class SysConfigService {
  private static Logger logger = LoggerFactory.getLogger(SysConfigService.class);

  private static String getTokenKey() {
    return WebchatServiceConstant.CACHE_KEY_ACCESS_TOKEN + WebchatServiceConstant.APPID;
  }

  private static String getTicketKey() {
    return WebchatServiceConstant.CACHE_KEY_JSTICKET + WebchatServiceConstant.APPID;
  }

  public static String getAccessToken() {
    EhCacheElement cachedToken = EhCacheFactory.get(getTokenKey());
    String token;
    AccessToken accessToken = new AccessToken();
    if (cachedToken == null) {
      accessToken = AccessTokenAPI.getAccessToken(WebchatServiceConstant.APPID, WebchatServiceConstant.APPSECRET);
      EhCacheElement cacheToken = new EhCacheElement();
      if (accessToken == null) {
        logger.debug("get access token failed");
        return null;
      } else {
        token = accessToken.getAccess_token();
        cacheToken.setObj(token);
        EhCacheFactory.add(getTokenKey(), cacheToken, accessToken.getExpires_in() - 200);
      }

    } else {
      token = (String)cachedToken.getObj();
    }
    return token;
  }

  public static String getJsTicket() {
    EhCacheElement cachedToken = EhCacheFactory.get(getTicketKey());
    String jsticket = null;
    String token = getAccessToken();
    // AccessToken accessToken = new AccessToken();
    JSTicket ticket = null;
    if (cachedToken == null) {
      ticket = JSTicketAPI.getJsTicket(token);
      EhCacheElement cacheToken = new EhCacheElement();
      jsticket = ticket.getTicket();
      cacheToken.setObj(jsticket);
      EhCacheFactory.add(getTicketKey(), cacheToken, ticket.getExpires_in() - 200);

    } else {
      jsticket = (String)cachedToken.getObj();
    }
    return jsticket;
  }

}
